package com.czxy;

import com.czxy.config.HighLightResultMapper;
import com.czxy.domain.Item;
import com.czxy.repository.ItemRepository;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ESApplication.class)
public class ESTest01 {
    /**
     * 使用SpringBootData家族提供的ElasticSearchTemplate
     */
    @Resource
    private ElasticsearchTemplate esTemplate;
    @Test
    public void createIndex() {
        // 创建索引，会根据Item类的@Document注解信息来创建
        esTemplate.createIndex(Item.class);
//        esTemplate.indexOps(Item.class);

        // 配置映射，会根据Item类中的id、Field等字段来自动完成映射
        esTemplate.putMapping(Item.class);
    }

    @Test
    public void deleteIndex() {
        esTemplate.deleteIndex(Item.class);
        // 根据索引名字删除
        //esTemplate.deleteIndex("item1");
    }
    @Autowired
    private ItemRepository itemRepository;



    @Test
    public void indexList() {
        List<Item> list = new ArrayList<>();
        list.add(new Item(1L, "小米手机7", "手机", "小米", 3299.00, "http://image.baidu.com/13123.jpg"));
        list.add(new Item(2L, "坚果手机R1", "手机", "锤子", 3699.00, "http://image.baidu.com/13123.jpg"));
        list.add(new Item(3L, "华为META10", "手机", "华为", 4499.00, "http://image.baidu.com/13123.jpg"));
        list.add(new Item(4L, "小米Mix2S", "手机", "小米", 4299.00, "http://image.baidu.com/13123.jpg"));
        list.add(new Item(5L, "荣耀V10", "手机", "华为", 2799.00, "http://image.baidu.com/13123.jpg"));
        // 接收对象集合，实现批量新增
        itemRepository.saveAll(list);
    }

    @Test
    public void index(){
        Item item = new Item(1L, "苹果XSMax", " 手机",
                "小米", 3499.00, "http://image.baidu.com/13123.jpg");
        itemRepository.save(item);
    }

    @Test
    public void testFindAll(){
        //1 查找所有
//        Iterable<Item> item = itemRepository.findAll();
//        Iterator<Item> it = item.iterator();
//        while (it.hasNext()){
//            System.out.println(it.next());
//        }
        //2 分页查找
//        Page<Item> page = itemRepository.findAll(PageRequest.of(1, 1));
//
//        for(Item item:page){
//            System.out.println(item);
//        }

        //3 排序
        Iterable<Item> iterable = itemRepository.findAll(Sort.by("price").descending());
        Iterator<Item> it = iterable.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }


    }

    /**
     * 自定义方法查询
     */
    @Test
    public void testMethods(){

//		List<Item> list = itemRepository.findByPriceBetween(3000.0, 6000.0);


//		List<Item> list = itemRepository.findByTitle("手机");

//		List<Item> list = itemRepository.findByPriceBetweenOrderByPriceDesc(1000.0,5000.0);

		List<Item> list = itemRepository.findByTitleAndPrice("坚果", 3699.0);

//		List<Item> list = itemRepository.findByTitleOrderByPriceDesc("iphone");

//        List<Item> list = itemRepository.findByBrandAndTitleAndPriceBetweenOrderByPriceDesc("华为", "20", 1000.0, 20000.0);

        for(Item i:list){
            System.out.println(i);
        }


    }
    @Test
    public void search(){
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        queryBuilder.withQuery(QueryBuilders.matchQuery("title", "小米手机"));
        // 搜索，获取结果
        Page<Item> items = this.itemRepository.search(queryBuilder.build());
        // 总条数
        long total = items.getTotalElements();
        System.out.println("total = " + total);
        for (Item item : items) {
            System.out.println(item);
        }
    }

    @Test
    public void testTermQuery(){

        // 查询条件生成器
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(QueryBuilders.termQuery("title","小米"));

        // 查询 自动分页 ,默认查找第一页的10条数据
        Page<Item> list = this.itemRepository.search(builder.build());

        for(Item item:list){
            System.out.println(item);
        }


    }

    @Test
    public void testFuzzyQuery(){
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(QueryBuilders.fuzzyQuery("title","Mixoo"));

        Page<Item> list = this.itemRepository.search(builder.build());
        for(Item item:list){
            System.out.println(item);
        }


    }
    @Test
    public void searchByPage(){
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        queryBuilder.withQuery(QueryBuilders.termQuery("category", "手机"));
        // 分页：
        int page = 0;
        int size = 2;
        queryBuilder.withPageable(PageRequest.of(page,size));

        // 搜索，获取结果
        Page<Item> items = this.itemRepository.search(queryBuilder.build());
        // 总条数
        long total = items.getTotalElements();
        System.out.println("总条数 = " + total);
        // 总页数
        System.out.println("总页数 = " + items.getTotalPages());
        // 当前页
        System.out.println("当前页：" + items.getNumber());
        // 每页大小
        System.out.println("每页大小：" + items.getSize());

        for (Item item : items) {
            System.out.println(item);
        }
    }
    @Test
    public void searchAndSort(){
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        queryBuilder.withQuery(QueryBuilders.termQuery("category", "手机"));

        // 排序
        queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));

        // 搜索，获取结果
        Page<Item> items = this.itemRepository.search(queryBuilder.build());
        // 总条数
        long total = items.getTotalElements();
        System.out.println("总条数 = " + total);

        for (Item item : items) {
            System.out.println(item);
        }
    }


    @Autowired
    private HighLightResultMapper highLightResultMapper;
    @Test
    public void testHL1(){
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.withQuery(QueryBuilders.fuzzyQuery("title","手机"))
                .withHighlightFields(new HighlightBuilder.Field("title")
                        //替换默认高亮标签<em></em>
                        .preTags("<em>").postTags("</em>"));

        // 执行查询
        Page<Item> page = esTemplate.queryForPage(queryBuilder.build(),Item.class,highLightResultMapper);

//        Page<Item> page = itemRepository.search(queryBuilder.build());

        for(Item item:page){
            System.out.println(item);
        }

    }



}
